using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using backend.Models.Dtos;
using backend.Repositories;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Services;

namespace backend.Controllers
{
    [EnableCors]
    [ApiController]
    [Route("api/stats")]
    public class StatsController : ControllerBase
    {
        
        private readonly StatsRepo _statsRepo;
        public StatsController(StatsRepo statsRepo)
        {
            _statsRepo = statsRepo;
        }

        [HttpGet]
        public async Task<IActionResult> GetStats(
            [FromQuery] int startYear = 1970,
            [FromQuery] int startMonth = 1,
            [FromQuery] int? endYear = null,
            [FromQuery] int? endMonth = null)
        {
            var principal = JwtHelper.GetAndValidateJwtToken(Request);
            if (principal == null)
            {
                return StatusCode(401, new { code = "failure", description = "Unauthorized" });
            }
            if (principal.Role != "2")
            {
                return StatusCode(403, new { code = "failure", description = "Forbidden" });
            }
            endYear ??= DateTime.Now.Year;
            endMonth ??= DateTime.Now.Month;

            var failureAreaStats = await _statsRepo.GetFailureAreaStatsAsync(
                startYear, startMonth, endYear, endMonth);

            var failureTypeStats = await _statsRepo.GetFailureTypeStatsAsync(
                startYear, startMonth, endYear, endMonth);

            var ratingStats = await _statsRepo.GetRatingStatAsync(
                startYear, startMonth, endYear, endMonth);

            var statsResult = new StatsResultDto
            {
                Faults = failureTypeStats,
                Areas = failureAreaStats,
                TotalAverage = ratingStats.TotalAverage,
                ResponseTime = ratingStats.ResponseTime, 
                ServiceQuality = ratingStats.ServiceQuality,
                ServiceAttitude = ratingStats.ServiceAttitude
            };

            return Ok(new
            {
                code = "success",
                data = statsResult
            });
        }
    }
}